﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Drawing.Design;
using System.Web;
using log4net;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	[DefaultProperty("Value")]
	[ToolboxData("<{0}:MyFileUpload runat=\"server\" ></{0}:MyFileUpload>")]
	public class MyFileUpload : WebControl, IScriptControl {
		private ILog m_logger = LogManager.GetLogger(typeof(MyFileUpload));

		private ScriptManager m_sm;

		private string m_uploadUrl;

		private string m_flashUrl;

		/// <summary>
		/// 
		/// </summary>
		[Bindable(false)]
		[Category("Appearance")]
		[DefaultValue("~/Upload.axd")]
		public string UploadUrl {
			get {
				return m_uploadUrl;
			}
			set {
				m_uploadUrl = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Bindable(false)]
		[Category("Appearance")]
		[DefaultValue("~/Common_Images/swfupload.swf")]
		public string FlashUrl {
			get {
				return m_flashUrl;
			}
			set {
				m_flashUrl = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor))]
		[UrlProperty]
		[DefaultValue("~/Common_Images/upload_button.png")]
		public string ImageUrl {
			get {
				return ViewState.Get<string>("ImageUrl", "~/Common_Images/upload_button.png");
			}
			set {
				ViewState["ImageUrl"] = value == null ? "" : value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Bindable(true)]
		[Category("Action")]
		[DefaultValue("*.*")]
		public string AcceptTypes {
			get {
				return ViewState.Get<string>("AcceptTypes", "*.*");
			}
			set {
				ViewState["AcceptTypes"] = value == null ? "" : value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Bindable(true)]
		[Category("Action")]
		[DefaultValue("All files(*.*)")]
		public string AcceptTypesDescription {
			get {
				return ViewState.Get<string>("AcceptTypesDescription", "All files(*.*)");
			}
			set {
				ViewState["AcceptTypesDescription"] = value == null ? "" : value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Bindable(true)]
		[Category("Action")]
		[DefaultValue(0)]
		public int MaxFileCount {
			get {
				return ViewState.Get<int>("MaxFileCount", 0);
			}
			set {
				ViewState["MaxFileCount"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[DefaultValue("61px")]
		public override Unit Width {
			get {
				return base.Width.IsEmpty ? new Unit(61, UnitType.Pixel) : base.Width;
			}
			set {
				if (value.Type != UnitType.Pixel) {
					base.Width = new Unit(61, UnitType.Pixel);
				} else {
					base.Width = value;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[DefaultValue("22px")]
		public override Unit Height {
			get {
				return base.Height.IsEmpty ? new Unit(22, UnitType.Pixel) : base.Height;
			}
			set {
				if (value.Type != UnitType.Pixel) {
					base.Height = new Unit(22, UnitType.Pixel);
				} else {
					base.Height = value;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Bindable(false)]
		[Browsable(false)]
		protected string SessionId {
			get {
				var ret = ViewState.Get<string>("SessionId", "");
				if (string.IsNullOrEmpty(ret)) {
					ret = Guid.NewGuid().ToString("N");
					ViewState["SessionId"] = ret;
				}

				return ret;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public MyFileUpload() {
			m_uploadUrl = "~/Upload.axd";
			m_flashUrl = "~/Common_Images/swfupload.swf";
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected System.Collections.Generic.IEnumerable<ScriptDescriptor> GetScriptDescriptors() {
			ScriptControlDescriptor descriptor = new ScriptControlDescriptor("MyLib.MyFileUpload", ClientID);
			descriptor.AddProperty("uploadUrl", VirtualPathUtility.ToAbsolute(this.UploadUrl));
			descriptor.AddProperty("flashUrl", ResolveClientUrl(this.FlashUrl));
			descriptor.AddProperty("sessionId", this.SessionId);
			descriptor.AddProperty("imageUrl", VirtualPathUtility.ToAbsolute(this.ImageUrl));
			descriptor.AddProperty("width", Width.Type == UnitType.Pixel ? Width.Value : 22);
			descriptor.AddProperty("height", Height.Type == UnitType.Pixel ? Height.Value : 61);
			descriptor.AddProperty("acceptTypes", this.AcceptTypes);
			descriptor.AddProperty("acceptTypesDescription", this.AcceptTypesDescription);
			descriptor.AddProperty("maxFileCount", this.MaxFileCount);
			descriptor.AddProperty("enabled", this.Enabled);

			return new ScriptDescriptor[] { descriptor };
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected System.Collections.Generic.IEnumerable<ScriptReference> GetScriptReferences() {
			return new ScriptReference[] { 
				new ScriptReference("MyLib.Web.swfupload.js", typeof(MyFileUpload).Assembly.FullName),
				new ScriptReference("MyLib.Web.MyFileUpload.js", typeof(MyFileUpload).Assembly.FullName)
			};
		}

		/// <summary>
		/// 
		/// </summary>
		protected override HtmlTextWriterTag TagKey {
			get {
				return HtmlTextWriterTag.Div;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnPreRender(EventArgs e) {
			if (!this.DesignMode) {
				// Test for ScriptManager and register if it exists
				m_sm = ScriptManager.GetCurrent(Page);

				if (m_sm == null)
					throw new HttpException("A ScriptManager control must exist on the current page.");

				m_sm.RegisterScriptControl(this);
			}

			base.OnPreRender(e);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer) {
			if (!this.DesignMode) {
				m_sm.RegisterScriptDescriptors(this);
			}

			base.Render(writer);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		protected override void RenderContents(HtmlTextWriter writer) {
			writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_placeholder");
			writer.RenderBeginTag(HtmlTextWriterTag.Span);
			writer.RenderEndTag();
		}

		#region IScriptControl

		IEnumerable<ScriptReference> IScriptControl.GetScriptReferences() {
			return GetScriptReferences();
		}

		IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors() {
			return GetScriptDescriptors();
		}

		#endregion
	} // end of MyFileUpload.
}
